import { Progress, Flex, Table, Button, Col, Row, Image } from "antd";
import { HeartFilled, HeartOutlined } from '@ant-design/icons';
import { screener_export, create_get_chart_task } from '../finviz'
import { TaskQueue } from '../queue'
import React, { useRef, useState } from "react";

function is_compliance(item) {
    for (let index = (item.close.length - 1); index > 0; index--) {

        const current_close = item.close[index];
        const previous_close = item.close[index - 1];

        const difference = current_close - previous_close;
        const percentage = (difference / previous_close) * 100;

        if (!(percentage > -1 && percentage < 1 && difference > -0.1 && difference < 0.1)) {
            return false;
        }
    }
    return true;
}

const TableColumns = [
    {
        title: '订阅',
        dataIndex: 'is_subscription',
        key: 'is_subscription',
        render: (_, record) => {
            return (
                <Button onClick={() => {
                    if (record.is_subscription) {
                        RemovefromsubscriptionList(record.ticker);
                    } else {
                        PushinsubscriptionList(record.ticker)
                    }
                    record.is_subscription = !record.is_subscription;
                }} icon={record.is_subscription ? <HeartFilled /> : <HeartOutlined />} />
            )
        }
    },
    {
        title: '代码',
        dataIndex: 'ticker',
        key: 'ticker',
    },
    {
        title: '开盘价',
        dataIndex: 'lastOpen',
        key: 'lastOpen',
    },
    {
        title: '最高价',
        dataIndex: 'lastHigh',
        key: 'lastHigh',
    },
    {
        title: '最低价',
        dataIndex: 'lastLow',
        key: 'lastLow',
    },
    {
        title: '收盘价',
        dataIndex: 'lastClose',
        key: 'lastClose',
    },
    {
        title: '成交量',
        dataIndex: 'lastVolume',
        key: 'lastVolume',
    },
    {
        title: '缩略图',
        dataIndex: 'tickerImage',
        key: 'tickerImage',
        render: (imageUrl) => <Image height={80} src={imageUrl} />
    },
]

const GetConfig = () => {
    if (window.localStorage.getItem('StockFilters') === 'null') {
        SetConfig({ subscriptionList: [] });
    }
    return JSON.parse(window.localStorage.getItem('StockFilters'));
}

const PushinsubscriptionList = (ticker) => {
    const config = GetConfig();
    config.subscriptionList.push(ticker);
    SetConfig(config);
}

const RemovefromsubscriptionList = (ticker) => {
    const config = GetConfig();
    config.subscriptionList = config.subscriptionList.filter(item => item !== ticker);
    SetConfig(config);
}

const SetConfig = (object) => {
    window.localStorage.setItem('StockFilters', JSON.stringify(object));
}

export const BigTicketScreening = React.forwardRef((props, ref) => {
    const componetData = useRef({
        ticketlist: [],
        percent: 0,
    });

    React.useImperativeHandle(ref, () => ({
        getData: () => componetData.current,
        setData: (data) => componetData.current = data,
    }))

    const [ticketlist, setTicketlist] = useState(componetData.current.ticketlist);
    const [percent, setPercent] = useState(componetData.current.percent);

    async function Refresh() {
        const csv = await screener_export('&f=sh_curvol_o200,sh_price_1to20,ta_change_-3to3&ft=4&o=-volume');
        const subscriptionlistSet = new Set(GetConfig().subscriptionList);
        componetData.current.ticketlist = [];
        const tasks = new TaskQueue(20);
        let count = 0;
        for (let index = 0; index < csv.length; index++) {
            const item = csv[index];
            tasks.addTask(create_get_chart_task(item.Ticker, 'd', true, false, 5)).then(data => {
                count++;
                const percent = ((count / csv.length) * 100).toFixed(2);

                if (is_compliance(data)) {
                    data.key = index;
                    data.is_subscription = subscriptionlistSet.has(data.ticker);
                    data.lastOpen = data.lastOpen.toFixed(2);
                    data.lastHigh = data.lastHigh.toFixed(2);
                    data.lastLow = data.lastLow.toFixed(2);
                    data.lastClose = data.lastClose.toFixed(2);
                    data.lastVolume = (data.lastVolume / 10000).toFixed(2) + 'W';
                    data.tickerImage = `https://charts-node.finviz.com/chart.ashx?&t=${data.ticker}&tf=d&s=linear&ct=candle_stick&tm=d`;

                    const newTicketlist = [...componetData.current.ticketlist, data];
                    componetData.current.ticketlist = newTicketlist;
                    setTicketlist(newTicketlist);
                }

                componetData.current.percentRef = Number(percent);
                setPercent(componetData.current.percentRef);
            });
        }
    }

    return (
        <>
            <Flex vertical gap="small">
                <Row>
                    <Col span={2}>
                        <Button onClick={Refresh}>重新查找</Button>
                    </Col>
                    <Col span={22}>
                        <Progress percent={percent} type="line" />
                    </Col>
                </Row>
            </Flex>
            <Table columns={TableColumns} dataSource={ticketlist}></Table>
        </>
    )
})
